package com.xbh.boot_study.annotion.valid.impl;

import cn.hutool.json.JSONUtil;
import com.xbh.boot_study.annotion.valid.ParamNoNullValid;
import com.xbh.boot_study.exception.ServiceException;
import com.xbh.boot_study.util.ValidUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import java.util.Set;

/**
 * 参数不空 验证器
 * 将验证类交给spring管理@Component@Scope("prototype")
 */
@Component
@Scope("prototype")
public class ParamNoNullValidator implements ConstraintValidator<ParamNoNullValid, Object> {

    private Class<?>[] groupings;

    /**
     * 初始化数据,获取注解里分组class数组
     */
    @Override
    public void initialize(ParamNoNullValid paramNoNullValid) {
        groupings = paramNoNullValid.groupings();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        if (null != value && !JSONUtil.parseObj(value).isEmpty()) {

            Set<ConstraintViolation<Object>> resultSet = ValidUtil.validate(value, groupings);
            if (resultSet.size() > 0) {
                throw new ServiceException(500, resultSet.stream().findAny().get().getMessage());
            }
            return true;
        }
        return false;
    }
}
